﻿
using AForge.Video.DirectShow;
using FW461DemoBLL;
using FW461DemoUtility;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FW461DemoMainUI {
    public partial class FormMain : Form {

        private int? PrevVideoWidth = null;
        private int? PrevVideoHeight = null;

        public FormMain(string[] args) {
            InitializeComponent();
        }

        private void BtnOpenFile_Click(object sender, EventArgs e) {
            var fv = new FileVideoSource(TxtOpenFile.Text);
            fv.VideoSourceError += Fv_VideoSourceError;
            VideoSourcePlayer.VideoSource = fv;
            VideoSourcePlayer.Start();
        }

        private void CheckAndResetPlayerSize(int videoWidth,int videoHeight) {
            if (PrevVideoWidth == videoWidth && PrevVideoHeight == videoHeight) {
                return;
            }
            PrevVideoWidth = videoWidth;
            PrevVideoHeight = videoHeight;
            Utilitys.AdaptSize(PanelPlayer.Size.Width, PanelPlayer.Size.Height, videoWidth, videoHeight,
                out var setWidth, out var setHeight, out var setTop, out var setLeft);
            VideoSourcePlayer.Invoke(new Action(()=> {
                VideoSourcePlayer.Width = setWidth;
                VideoSourcePlayer.Height = setHeight;
                VideoSourcePlayer.Top = setTop;
                VideoSourcePlayer.Left = setLeft;
            }));
        }

        private void FormMain_Load(object sender, EventArgs e) {
            VideoSourcePlayer.NewFrame += VideoSourcePlayer_NewFrame;

        }

        private void VideoSourcePlayer_NewFrame(object sender, ref Bitmap image) {
            CheckAndResetPlayerSize(image.Width, image.Height);
            using (var g = Graphics.FromImage(image)) {
                //加个水印
                BVideo.DrawWatermark(g, Properties.Resources.logo_130x80);
            }
        }

        private void Fv_VideoSourceError(object sender, AForge.Video.VideoSourceErrorEventArgs eventArgs) {
            MessageBox.Show("播放错误:" + eventArgs.Description);
        }

        private void FormMain_FormClosed(object sender, FormClosedEventArgs e) {
            try {
                if (VideoSourcePlayer.VideoSource != null) {
                    VideoSourcePlayer.VideoSource.VideoSourceError -= Fv_VideoSourceError;
                }
                VideoSourcePlayer?.Stop();
                VideoSourcePlayer?.Dispose();
            } catch (Exception ex){
                var eee = ex;
            }
        }
    }
}
